﻿// Gateway.Api 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Aurora.AI.Common.Constants;
using Aurora.AI.Common.Extensions;
using Aurora.AI.Common.Helper;
using Aurora.AI.Common.Models;
using Aurora.AI.SqlSugar.Framework.Repositories;
using Aurora.AI.Wiki.Domain.Domain;
using Aurora.Redis;

namespace Aurora.AI.Wiki.Services;

/// <summary>
/// 配置服务 open ai
/// </summary>
public class WikiSettingService(IRepository<Setting> repository, IRedisCache redisCache)
{
    /// <summary>
    /// 更新ai 设置
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task Update(AICommonSetting request)
    {
        if (request != null)
        {
            await UpdateSettingsAsync("Setting:Common", AuroraAIJsonSerializer.Serialize(request));
            string key = CacheConstant.CommonSettingCacheKey;
            await redisCache.DelAsync(key);
        }
    }
    
    /// <summary>
    /// 获取通用的 ai 设置
    /// </summary>
    /// <returns></returns>
    public async Task<AICommonSetting> GetCommonSetting()
    {
        string key = CacheConstant.CommonSettingCacheKey;
        AICommonSetting aiCommonSetting = await redisCache.GetAsync<AICommonSetting>(key);
        if (aiCommonSetting != null)
            return aiCommonSetting;
        AICommonSetting commonSetting = await GetSetting<AICommonSetting>("Setting:Common");
        await redisCache.AddAsync(key, commonSetting, TimeSpan.FromHours(24));
        return commonSetting;
    }

    /// <summary>
    /// 获取所有的
    /// </summary>
    /// <returns></returns>
    public async Task<List<Setting>> GetAllAsync()
    {
        return await repository.GetListAsync(x => x.IsDeleted == false);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    private async Task<string> GetSettingByKey(string key)
    {
        return (await repository.GetFirstAsync(x => x.Key == key))?.Value ?? string.Empty;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    private async Task<T> GetSetting<T>(string key)
    {
        var value = await GetSettingByKey(key);
        return string.IsNullOrEmpty(value) ? default : AuroraAIJsonSerializer.Deserialize<T>(value);
    }

    /// <summary>
    /// 更新设置
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    private async ValueTask UpdateSettingsAsync(string key, string value)
    {
        var dbSettings = await repository.GetFirstAsync(x => x.Key.Equals(key));
        if (dbSettings != null)
        {
            dbSettings.Value = value;
            dbSettings.ModificationTime = DateTime.Now;
            await repository.UpdateAsync(dbSettings);
            await redisCache.DelAsync(key);
        }
        else
        {
            dbSettings = new()
            {
                Id = IdHelper.GenerateId(),
                Key = key,
                Value = value,
                CreationTime = DateTime.Now,
                Description = key,
                IsDeleted = false
            };
            await repository.InsertAsync(dbSettings);
            await redisCache.DelAsync(key);
        }
    }
}